import { _decorator, Component, find, instantiate, Node, Prefab, Sprite, sys, TransformBit, UITransform } from 'cc';
import { toolsScript } from './toolsScript';
const { ccclass, property } = _decorator;

@ccclass('ScoreManager')
export class ScoreManager extends Component {
    SocreInitPosX:number = -28.296;
    ScoreInitPosY:number = 38.102;

    @property([Prefab]) 
    ScoreNodeprefabList: Prefab[] = [];

    ScoreNodeList:Node[]=[];

    start() {
        //延迟1侦
        this.scheduleOnce(() => {
            this.calScore();
        });
    }

    update(deltaTime: number) {
        
    }

    protected onDestroy(): void {
        if(this.ScoreNodeList.length > 0)
            {
                for (let index = 0; index < this.ScoreNodeList.length; index++) {
                    const element = this.ScoreNodeList[index];
                    this.node.removeChild(element);
                    element.destroy();
                }
            }
    
            this.ScoreNodeList=[];
    }
    
    calScore()
    {
        
        let topRecordString:string = toolsScript.getItem('topRecord');
        console.log("get value : ",topRecordString,"lengh : ",topRecordString.length)
        if(topRecordString == null || topRecordString.length <= 0)
        {
            topRecordString = "0";
        }

        const ScoreStr = topRecordString.toString(); // 转换为字符串
        const ScoreChars = Array.from(ScoreStr, Number); // 分割为单个字符

        const recordNode = this.node.getChildByName("Record");
        if(recordNode == null)
        {
            console.error("can not get recordNode");
            return;
        }

        let lastNumber = 0;
        for (let row = 0; row < ScoreChars.length; row++) 
        {
            // 获取图片节点
            const imageNode = this.ScoreNodeprefabList[ScoreChars[row]];
            if(imageNode == null)
            {
                console.error("imageNode1 IS NULL");
            }
            else
            {
                const ScoreImg = instantiate(imageNode);
                if(row <= 0)
                {
                    ScoreImg.setPosition(recordNode.position.x+170,0,0);
                    lastNumber = ScoreImg.position.x;
                }
                else
                {
                    ScoreImg.setPosition(lastNumber+42,0,0);
                    lastNumber = ScoreImg.position.x;
                }
                
                console.log("----- Get Number : ",ScoreChars[row]," Pos : ",ScoreImg.position)

                let Transform = ScoreImg.getComponent(UITransform);
                Transform.width = 48;
                Transform.height = 56;
                this.node.addChild(ScoreImg); 

                this.ScoreNodeList.push(ScoreImg);
            }
        }
    }

    public gameOver()
    {
        this.calScore();
    }

}


